<?php 

/**
 *Ajax TO cart
 */
require_once("Mage/Checkout/controllers/CartController.php");
class Silk_Qslb_CartController extends Mage_Checkout_CartController
{
	public function addAjaxAction()
    {
        $data = array('code'=>200,'message'=>'');

        $cart   = $this->_getCart();
        $params = $this->getRequest()->getParams();

        try {
            if (isset($params['qty'])) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                $params['qty'] = $filter->filter($params['qty']);
            }

            $product = $this->_initProduct();

            $related = $this->getRequest()->getParam('related_product');

            /**
             * Check product availability
             */
            if (!$product) {
                throw new Exception("商品不存在！");
            }

            //var_dump($product->getVisibility());exit;
            if($product->getVisibility()!=4)
            {
                throw new Exception("商品不存在！");
            }

            $cart->addProduct($product, $params);
            if (!empty($related)) {
                $cart->addProductsByIds(explode(',', $related));
            }

            $cart->save();


            $totalItems = $cart->getQuote()->getItemsCount();
            $data['count'] = $totalItems;
            $data['subtotal'] = $cart->getQuote()->getsubtotal();
            $data['grandTotal'] = $cart->getQuote()->getGrandTotal();

            $this->_getSession()->setCartWasUpdated(true);

            /**
             * @todo remove wishlist observer processAddToCart
             */
            Mage::dispatchEvent('checkout_cart_add_product_complete',
                array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
            );

        } catch (Exception $e) {
            
            $data = array('code'=>500,'message'=>$e->getMessage());
        }

        echo json_encode($data);
    }

    /**
     * Update shopping cart data action
     */
    public function updatePostAction()
    {
        if (!$this->_validateFormKey()) {
            $this->_redirect('*/*/');
            return;
        }

        $updateAction = (string)$this->getRequest()->getParam('update_cart_action');
        $ret = false;
        switch ($updateAction) {
            case 'empty_cart':
                $this->_emptyShoppingCart();
                break;
            case 'update_qty':
                $ret = $this->_updateShoppingCart();
                break;
            default:
                $this->_updateShoppingCart();
        }

        if($updateAction == 'update_qty' && $ret)

        {
            $this->_redirect('checkout/onepage');
        }
        else
        {
            $this->_goBack();
        }

    }

    public function ajaxUpdateAction(){
        $data = [];
        if (!$this->_validateFormKey()) {
            $this->_redirect('*/*/');
            return;
        }

        if($this->_updateShoppingCart())
        {
            $data['price'] = number_format(Mage::getModel('checkout/cart')->getQuote()->getGrandTotal(),2);
            $data['count'] = Mage::getModel('checkout/cart')->getSummaryQty();
        }
        echo json_encode($data);
        //$this->_redirect('checkout/cart');

    }

    public function preDispatch()
    {
        Mage_Core_Controller_Front_Action::preDispatch();
        //var_dump($_SERVER['HTTP_REFERER']);exit;
        $session = Mage::getSingleton('customer/session');
        $urlHelper = Mage::helper('core/url');
        if(!$session->isLoggedIn())
        {
            $this->_redirect('customer/account/login', array('referer'=>$urlHelper->getEncodedUrl()));
        }
        $cart = $this->_getCart();
        if ($cart->getQuote()->getIsMultiShipping()) {
            $cart->getQuote()->getIsMultiWarehouse(null);
            $cart->getQuote()->setIsMultiShipping(false);
        }

        return $this;
    }

    protected function _updateShoppingCart()
    {
        try {
            $cartData = $this->getRequest()->getParam('cart');
            if (is_array($cartData)) {
                $filter = new Zend_Filter_LocalizedToNormalized(
                    array('locale' => Mage::app()->getLocale()->getLocaleCode())
                );
                foreach ($cartData as $index => $data) {
                    if (isset($data['qty'])) {
                        $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
                    }
                }
                $cart = $this->_getCart();
                if (! $cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
                    $cart->getQuote()->setCustomerId(null);
                }

                $cartData = $cart->suggestItemsQty($cartData);
                $cart->updateItems($cartData)
                    ->save();
            }
            $this->_getSession()->setCartWasUpdated(true);
            return true;
        } catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError(Mage::helper('core')->escapeHtml($e->getMessage()));
        } catch (Exception $e) {
            $this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
            Mage::logException($e);
        }
        return false;
    }

    protected function _initProduct()
    {
        $productId = (int) $this->getRequest()->getParam('product');
        if(!$productId)
        {
            $sku = $this->getRequest()->getParam('sku');
            if($sku) $productId = Mage::getModel('catalog/product')->getIdBySku($sku);
        }
        if ($productId) {
            $product = Mage::getModel('catalog/product')
                ->setStoreId(Mage::app()->getStore()->getId())
                ->load($productId);
            if ($product->getId()) {
                return $product;
            }
        }
        return false;
    }

    /**
     * Delete shoping cart item action core_write core_read
     */
    public function deleteAction()
    {
        $quoteId = $this->_getQuote()->getId();
        if ($this->_validateFormKey()) {
            $id = (int)$this->getRequest()->getParam('id');
            if ($id) {
                try {
                    //$this->_getQuote()->removeItem($id)->save();
                    $db = Mage::getSingleton('core/resource')->getConnection('core_write');
                    $sql = "delete from sales_flat_quote_item where quote_id = {$quoteId} AND product_id = {$id}";
                    $query = $db->query($sql);
                    $query->fetchAll();
                } catch (Exception $e) {
                    $this->_getSession()->addError($this->__('Cannot remove the item.'));
                    Mage::logException($e);
                }
            }
        } else {
            $this->_getSession()->addError($this->__('Cannot remove the item.'));
        }

        $this->_redirectReferer(Mage::getUrl('*/*'));
    }
}